/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
 * @author Sergey I. Salishev
 */
package org.apache.cgiservlet;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Map;

import org.jruby.Ruby;
import org.jruby.RubyInstanceConfig;
import org.jruby.RubyInstanceConfig.CompileMode;
import org.jruby.RubyInstanceConfig.LoadServiceCreator;

/**
 * Ruby CGI servlet
 */
public class RubyServlet extends CGIServlet {

	private static final long serialVersionUID = 1L;

	private ThreadLocal<Ruby> runtime = new ThreadLocal<Ruby>();
	private ThreadLocal<File> script = new ThreadLocal<File>();
	
	private final LoadServiceCreator cache =  new RubyCachedLoadServiceCreator();
	
	@Override
	protected void runScript() throws IOException {
		try {
			runtime.get().getLoadService().smartLoad(script.get().getAbsolutePath());
		} finally {
			runtime.get().tearDown();
		}
	}

	public RubyServlet() {
	}
	
	Ruby old;

	@Override
	protected void prepareScript(final String[] args,
			final Map<String, String> env, final InputStream in,
			final OutputStream out, final File scriptFile) throws IOException {

		RubyInstanceConfig config = new RubyInstanceConfig();
		
		config.setCompileMode(CompileMode.OFF);
		config.setLoadServiceCreator(cache);

		config.setArgv(args);
		config.setEnvironment(env);
		config.setCurrentDirectory(scriptFile.getParent());

		config.setOutput(new PrintStream(out));
		config.setInput(in);
						
		Ruby ruby = Ruby.newInstance(config);
		
		runtime.set(ruby);
		
		script.set(scriptFile);
	}
}
